package Controller;

import Model.MySportBean;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

@WebServlet("/MySport")
public class MySport extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        HttpSession session = request.getSession();
        String id = (String) session.getAttribute("id");
        Connection con=null;
        PreparedStatement pstmt=null;
        String sql;
        ResultSet rs;
        PrintWriter out=response.getWriter();
        try{  //加载JDBC-MySQL8.0连接器:
            Class.forName("com.mysql.cj.jdbc.Driver");
        }
        catch(Exception e){
            out.println("加载失败");
        }
        String url = "jdbc:mysql://localhost:3306/yundonghui?"+
                "useSSL=false&serverTimezone=CST&characterEncoding=utf-8";
        String user ="root";
        String password ="123456";
        try {
            con = DriverManager.getConnection(url,user,password);
            sql="select score.sno,sname,stime,splace from score natural join sport where id=?";
            pstmt = con.prepareStatement(sql);
            pstmt.setString(1,id);
            rs = pstmt.executeQuery();
            MySportBean db = (MySportBean)session.getAttribute("mysportBean");
            if(db==null){
                db = new MySportBean();
            }
            MySportBean temp = new MySportBean();
            Model.MySport d;
            int sum = 0;
            while (rs.next()){
                d = new Model.MySport();
                d.setSno(rs.getString(1));
                d.setSname(rs.getString(2));
                d.setStime(rs.getString(3));
                d.setSplace(rs.getString(4));
                temp.add(d);
            }
            con.close();
            db.setMySports(temp.getMySports());
//            db.setSum_price(sum);
            session.setAttribute("mysportBean",db);
            response.sendRedirect("sporter/mySport.jsp");
        } catch (SQLException e) {
            out.println("连接失败");
        }//连接数据库。
    }
}
